﻿#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <limits.h>

int my_atoi(const char* str) {
    // 处理空指针
    if (str == NULL) {
        return 0;
    }

    int result = 0;
    int sign = 1;  // 符号位，1表示正数，-1表示负数
    int i = 0;

    // 跳过前导空白字符
    while (isspace(str[i])) {
        i++;
    }

   
    if (str[i] == '-' || str[i] == '+')
    {
        sign = (str[i] == '-') ? -1 : 1;
        i++;
    }
    while (str[i] >= '0' && str[i] <= '9')
    {

        if (result > INT_MAX / 10 ||
            (result == INT_MAX / 10 && (str[i] - '0') > INT_MAX % 10))
        {
            return (sign == 1) ? INT_MAX : INT_MIN;

        }
        result = result * 10 + (str[i] - '0');
        i++;

    }
              

    return sign * result;
}
int main()
{
    char a[] = "102345";
    printf("%d\n", my_atoi(a));
    // 测试边界情况
    printf("%d\n", my_atoi("2147483647"));  // INT_MAX
    printf("%d\n", my_atoi("-2147483648")); // INT_MIN
    printf("%d\n", my_atoi("2147483648"));  // 溢出，返回 INT_MAX
}